package com.mqy.ssm.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mqy.ssm.cache.SceneCache;
import com.mqy.ssm.event.SceneEvent;
import com.mqy.ssm.exception.MyBaseException;
import com.mqy.ssm.mapper.BookMapper;
import com.mqy.ssm.pojo.Book;
import com.mqy.ssm.service.BookService;
import com.mqy.ssm.utlic.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 13159 //作者
 * @version V1.0 //版本
 * @Project case1
 * @Package com.mqy.ssm.service.Impl
 * @Description:
 * @Date 2022/3/10 10:26//日期
 * @Motto:放下杂念,只为迎接明天更好的自己
 */

@Service
@Transactional
public class BookServiceImpl implements BookService {
    BookMapper bookMapper;

    @Autowired
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    /*注入的东西*/
    private SceneCache sceneCache;

    @Autowired
    public void setSceneCache(SceneCache sceneCache) {
        this.sceneCache = sceneCache;
    }

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public Book findID(Long id) {
        return bookMapper.findID(id);
    }

    @Override
    public PageInfo<Book> findAll(int pageSize, int pageNum) {

        PageHelper.startPage(pageNum,pageSize);
//        List<SysScene> sceneList = sysSceneMapper.findAll();
//        PageInfo<SysScene> pageInfo = new PageInfo<>(sceneList);
        List<Book> sceneList = sceneCache.getAllData();//所有的数据
        //上面是所有的数据.我们要裁减一部分
        List<Book> sysSceneList = sceneList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<Book> pageInfo = new PageInfo<>(sysSceneList);
        pageInfo.setTotal(sceneList.size());//单独设置一次总长度
        return pageInfo;
    }

    @Override
    public void bookAdd(Book book) {
        Assert.isTrue(!book.isEmpty(), () -> {
            throw new MyBaseException("传递数据不能为空", ResultCode.DATA_EMPTY);
        });
        bookMapper.bookAdd(book);
        /*发布一个事务*/
        context.publishEvent(new SceneEvent());
    }

    @Override
    public void boodremove(Long id) {
        bookMapper.boodremove(id);
        /*发布一个事务*/
        context.publishEvent(new SceneEvent());
    }

    @Override
    public void bookupdate(Book book) {
        Assert.isTrue(!book.isEmpty(), () -> {
            throw new MyBaseException("传递数据不能为空", ResultCode.DATA_EMPTY);
        });
        bookMapper.bookupdate(book);
        /*发布一个事务*/
        context.publishEvent(new SceneEvent());
    }
}
